import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_picker/flutter_picker.dart';
import 'package:hbtrans_flutter/apis.dart';
import 'package:hbtrans_flutter/beans/UserUpdateBean.dart';
import 'package:hbtrans_flutter/const.dart';
import 'package:hbtrans_flutter/routes.dart';
import 'package:hbtrans_flutter/utils/mydio.dart';
import 'package:hbtrans_flutter/view/loading.dart';
import 'package:shared_preferences/shared_preferences.dart';

class ImproveInformation extends StatefulWidget {
  @override
  _ImproveInformationState createState() => _ImproveInformationState();
}

class _ImproveInformationState extends State<ImproveInformation> {
  LoadingDialog loadingDialog;
  Map<String, dynamic> userupdate = Map();
  var id = '';
  var phone = '';
  var classes = ['男', '女'];
  String sextype = '请选择性别';
  var _scaffoldKey = GlobalKey<ScaffoldState>();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getUserId();
  }

  void _getUserId() async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    id = sp.getString('id');
    userupdate['id'] = id;
    userupdate['phone'] = sp.getString('phone');
  }

  _showPickerIcons(BuildContext context) {
    Picker(
      adapter: PickerDataAdapter(data: _setPickerItems()),
      title: Text(''),
      cancelText: '取消',
      confirmText: '确定',
      selectedTextStyle: TextStyle(color: Colors.blue),
      onConfirm: (Picker picker, List value) {
        sextype = classes[value[0]];
        userupdate['sex'] = sextype;
        setState(() {});
      },
    ).show(_scaffoldKey.currentState);
  }

  _setPickerItems() {
    List<PickerItem<dynamic>> pickerItems = List();
    for (String s in classes) {
      pickerItems.add(PickerItem(
          value: Icons.add,
          text: Text(s,
              style: TextStyle(color: const Color(0xff333333), fontSize: 16))));
    }
    return pickerItems;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor:Colors.white ,
      key: _scaffoldKey,
      appBar: AppBar(
        title: const Text(
          '完善信息',
          style: TextStyle(color: Colors.white),
        ),
        backgroundColor: Color(0xff23AFDC),
        centerTitle: true,
        actions: <Widget>[
          Center(
              child: GestureDetector(
            onTap: () {
              _userUpdate();
            },
            child: Text(
              '完成',
              style: TextStyle(fontSize: 16, color: Colors.white),
            ),
          ))
        ],
      ),
      body: Padding(
        padding: const EdgeInsets.fromLTRB(20, 50, 20, 20),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Column(
              children: <Widget>[
                Row(
//                  mainAxisAlignment: MainAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      '姓名',
                      style: TextStyle(
                          fontSize: 14, color: const Color(0xff333333)),
                    ),
                    SizedBox(
                      width: 55,
                    ),
                    Expanded(
                      child: MyTextField(
                        mapKey: 'name',
                        data: userupdate,
                        hintText: '请输入姓名',
                      ),
                    )
                  ],
                ),
                SizedBox(
                  height: 30,
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      '身份证号',
                      style: TextStyle(
                          fontSize: 14, color: const Color(0xff333333)),
                    ),
                    SizedBox(
                      width: 26,
                    ),
                    MyTextField(
                      hintText: '请输入身份证号',
                      mapKey: 'idcard',
                      data: userupdate,
                    ),
                  ],
                ),
                SizedBox(
                  height: 30,
                ),
                GestureDetector(
                  onTap: () {
                    _showPickerIcons(context);
                  },
                  child: SizedBox(
                    height: 50,
                    child: Card(
                      margin: EdgeInsets.all(0),
                      elevation: 0,
                      color: Colors.white,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[
                          Text(
                            '性别',
                            style: TextStyle(
                                fontSize: 14, color: Color(0xff333333)),
                          ),
                          Text(
                            sextype,
                            style: TextStyle(
                                fontSize: 14, color: Color(0xff666666)),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
//                Row(
//                  mainAxisAlignment: MainAxisAlignment.start,
//                  children: <Widget>[
//                    Text(
//                      '联系电话',
//                      style: TextStyle(
//                          fontSize: 14, color: const Color(0xff333333)),
//                    ),
//                    SizedBox(
//                      width: 26,
//                    ),
//                    MyTextField(
//                      hintText: '请输入电话',
//                      mapKey: 'phone',
//                      data: userupdate,
//                    ),
//                  ],
//                ),
//                SizedBox(
//                  height: 20,
//                ),
//                Text(
//                  '您所填写的身份信息仅用于购买APP商品',
//                  style: TextStyle(
//                    fontSize: 10,
//                    color: const Color(0xff999999),
//                  ),
//                )
              ],
            ),
//            MaterialButton(
//              minWidth: MediaQuery.of(context).size.width,
//              elevation: 0,
//              onPressed: () {},
//              child: Text(
//                "完成",
//                style: TextStyle(color: Colors.white, fontSize: 16),
//              ),
//              color: Color(0xff23AFDC),
//              shape: RoundedRectangleBorder(
//                  borderRadius: BorderRadius.all(Radius.circular(20))),
//            ),
          ],
        ),
      ),
    );
  }

  _showDialog() {
    loadingDialog = LoadingDialog(
      text: '请稍候...',
    );
    showDialog<Null>(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return loadingDialog;
        });
  }

  void _userUpdate() async {
    _showDialog();
    SharedPreferences sp = await SharedPreferences.getInstance();
    var header = Map<String, String>();
    header['token'] = sp.getString('token');
    Options options = Options(headers: header);
    var url='http://47.92.133.160:1304/mall//order/tuser/UserUpdate';
    Response response=await Dio().post(url,queryParameters: userupdate,options: options);
    setState(() {
      var result=response.toString();
      var mydata=json.decode(result);
      if(mydata['code']==0){
        String route = '${Routes.mainPage}';
      Routes.router.navigateTo(context, route,
          replace: true, transition: TransitionType.fadeIn);
      }
    });

//    MyDio.getInstance(url: Const.TRANS_SERVER_PATH_NEW3)
//        .post(Apis.updateUserInfo, (data) {
//      print(data);
//      if (loadingDialog != null) {
//        loadingDialog = null;
//        Navigator.pop(context);
//      }
//
//
//    }, params: userupdate,);
  }
}

class MyTextField extends StatelessWidget {
  final imageSrc;
  final hintText;
  final readOnly;
  final data;
  final mapKey;

  const MyTextField(
      {Key key,
      this.imageSrc,
      this.hintText,
      this.readOnly,
      this.data,
      this.mapKey})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return TextFormField(
      onChanged: (value) {
        data[mapKey] = value;
      },
      textAlign: TextAlign.right,
      readOnly: readOnly == null ? false : readOnly,
      keyboardType: TextInputType.number,
      style: TextStyle(fontSize: 14, color: Color(0xff999999)),
      textCapitalization: TextCapitalization.words,
      decoration: InputDecoration(
        border: InputBorder.none,
//        focusedBorder: UnderlineInputBorder(
//            borderSide: BorderSide(color: Color(0xffE4E4E4))),
//        enabledBorder: UnderlineInputBorder(
//            borderSide: BorderSide(color: Color(0xffE4E4E4))),
        fillColor: Colors.transparent,
        filled: true,
        icon: Image.asset(
          imageSrc,
          height: 24,
          width: 24,
          fit: BoxFit.fill,
        ),
        hintText: hintText,

        hintStyle: TextStyle(fontSize: 14, color: Color(0xff999999)),
      ),
    );
  }
}
